package com.zuofei.xmpp.service;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.zuofei.xmpp.activity.LoginActivity;
import com.zuofei.xmpp.dbhelper.ContactOpenHelper;
import com.zuofei.xmpp.dbhelper.SmsOpenHelper;
import com.zuofei.xmpp.provider.ContactsProvider;
import com.zuofei.xmpp.provider.SmsProvider;
import com.zuofei.xmpp.utils.PinyinUtil;
import com.zuofei.xmpp.utils.ThreadUtils;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class IMService extends Service {
    public static XMPPConnection connection;
    public static String mCurAccount;//当前登陆用户的jid
    private Roster mRoster;
    private MyRosterListener mRosterListener;

    private ChatManager mChatManager;
    private Chat mCurChat;
    private Map<String,Chat> mChatMap = new HashMap<>();

    @Override
    public void onCreate() {
        /**同步花名册*/
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                //得到花名册
                mRoster = IMService.connection.getRoster();

                //得到所有的联系人
                final Collection<RosterEntry> entries = mRoster.getEntries();

                //监听联系人的改变
                mRosterListener = new MyRosterListener();
                mRoster.addRosterListener(mRosterListener);

                for (RosterEntry entry : entries) {
                    saveOrUpdateEntry(entry);
                }
                //注册消息的监听
                if (mChatManager == null) {
                    mChatManager = IMService.connection.getChatManager();
                }
                mChatManager.addChatListener(mMyChatManagerListener);
            }
        });
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder{
        /**
         * 返回service的实例
         */
        public IMService getService(){
            return IMService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        //移除rosterListener
        if (mRoster != null && mRosterListener != null) {
            mRoster.removeRosterListener(mRosterListener);
        }
        //移除消息监听
        if (mCurChat != null && mMyMessageListener != null) {
            mCurChat.removeMessageListener(mMyMessageListener);
        }
        super.onDestroy();
    }

    /**
     * 保存或更新数据
     *
     * @param entry
     */
    private void saveOrUpdateEntry(RosterEntry entry) {
        ContentValues values = new ContentValues();
        String account = entry.getUser();
        account = account.substring(0, account.indexOf("@")) + "@" + LoginActivity.SERVICE_NAME;
        String nickname = entry.getName();
        values.put(ContactOpenHelper.ContactTable.ACCOUNT, account);

        if (nickname == null || "".equals(nickname)) {
            nickname = account.substring(0, account.indexOf("@"));
        }
        values.put(ContactOpenHelper.ContactTable.NICKNAME, nickname);
        values.put(ContactOpenHelper.ContactTable.AVATAR, "0");
        values.put(ContactOpenHelper.ContactTable.PINYIN, PinyinUtil.getPinyin(account));
        //先update，后插入
        int updateCount = getContentResolver().update(ContactsProvider.URI_CONTACT, values, ContactOpenHelper.ContactTable.ACCOUNT + "=?", new String[]{account});
        if (updateCount <= 0) { //没有更新到任何记录
            getContentResolver().insert(ContactsProvider.URI_CONTACT, values);
        }
    }

    /**
     * @param msg            消息
     * @param sessionAccount 会话人id
     */
    private void saveMessage(Message msg, String sessionAccount) {
        ContentValues values = new ContentValues();
        values.put(SmsOpenHelper.SMSTable.FROM_ACCOUNT, msg.getFrom());
        values.put(SmsOpenHelper.SMSTable.TO_ACCOUNT, msg.getTo());
        values.put(SmsOpenHelper.SMSTable.BODY, msg.getBody());
        values.put(SmsOpenHelper.SMSTable.STATUS, "offline");
        values.put(SmsOpenHelper.SMSTable.TYPE, msg.getType().name());
        values.put(SmsOpenHelper.SMSTable.TIME, System.currentTimeMillis());
        values.put(SmsOpenHelper.SMSTable.SESSION_ACCOUNT, sessionAccount);//当前用户id
        getContentResolver().insert(SmsProvider.URI_SMS, values);
    }

    public void sendMessage(final Message msg) {
        try {
            //判断chat
            String toAccount = msg.getTo();
            if(mChatMap.containsKey(toAccount)){
                mCurChat = mChatMap.get(toAccount);
            }else {
                mCurChat =  mChatManager.createChat(msg.getTo(), mMyMessageListener);
                mChatMap.put(toAccount,mCurChat);
            }
            //发送消息
            mCurChat.sendMessage(msg);
            //保存消息
            saveMessage(msg, msg.getTo());
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }

    /**
     * 联系人监听类
     */
    private class MyRosterListener implements RosterListener {
        @Override
        public void entriesAdded(Collection<String> collection) {
            for (String address : collection) {
                RosterEntry entry = mRoster.getEntry(address);
                //要么更新，要么插入
                saveOrUpdateEntry(entry);
            }
        }

        @Override
        public void entriesUpdated(Collection<String> collection) {
            for (String address : collection) {
                RosterEntry entry = mRoster.getEntry(address);
                //要么更新，要么插入
                saveOrUpdateEntry(entry);
            }
        }

        @Override
        public void entriesDeleted(Collection<String> collection) {
            for (String account : collection) {
//                RosterEntry entry = mRoster.getEntry(address);
                //执行删除操作
                getContentResolver().delete(ContactsProvider.URI_CONTACT, ContactOpenHelper.ContactTable.ACCOUNT + "=?", new String[]{account});
            }
        }

        @Override
        public void presenceChanged(Presence presence) {

        }
    }

    MyMessageListener mMyMessageListener = new MyMessageListener();
    /**
     * 消息接受
     */
    class MyMessageListener implements MessageListener {

        @Override
        public void processMessage(Chat chat, Message message) {
            //收到消息,保存消息
            String participant = chat.getParticipant(); //参与值的账号，我和参与值会话
            saveMessage(message, participant);
        }
    }

    MyChatManagerListener mMyChatManagerListener = new MyChatManagerListener();
    class MyChatManagerListener implements ChatManagerListener{

        @Override
        public void chatCreated(Chat chat, boolean b) {
            //判断chat是否存在map里面
            String participant = chat.getParticipant();//我现在和谁在聊天
            participant = participant.substring(0,participant.indexOf("@")) +"@"+LoginActivity.SERVICE_NAME;
            if(!mChatMap.containsKey(participant)){
                mChatMap.put(participant,chat);
                chat.addMessageListener(mMyMessageListener);
            }
            if(b){ //自己创建的chat

            }else{ //其他人创建的chat

            }
        }
    }
}
